package service

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"lot_admin_api/internal/model"
	"lot_admin_api/utility/paging"
)

type sStatistics struct{}

var (
	insStatistics = sStatistics{}
)

func Statistics() *sStatistics {
	return &insStatistics
}

// UserDynamic  用户动态
func (s *sStatistics) UserDynamic(ctx context.Context, req *model.GetUserDynamic) (res []*model.UserDynamicRes, err error) {

	// 获取分页偏移量
	startNum, endNum := paging.Paging(req.Paging)
	// 部门的递归查询sql
	searchSql := `
				SELECT
					* 
				FROM
					(
					SELECT
						rechargeRecord.user_id AS id,
						rechargeRecord.id AS rechargeRecordId,
						'' AS orderId,
						'1' AS type,
						users.head_img as headImg,
						users.username,
						'' AS siteName,
						'' AS siteId,
						rechargeRecord.give_type AS giveType,
						rechargeRecord.recharge_money AS rechargeMoney,
						rechargeRecord.give_money AS giveMoney,
						rechargeRecord.created_at AS createdAt,
						rechargeRecord.updated_at AS updatedAt 
					FROM
						lot_user users,
						lot_site sites,
						lot_recharge_record rechargeRecord 
					WHERE
						rechargeRecord.deleted_at IS NULL 
						AND users.id = rechargeRecord.user_id UNION
					SELECT
						orders.user_id AS id,
						'' AS rechargeRecordId,
						orders.id AS orderId,
						'2' AS type,
						users.head_img as headImg,
						users.username,
						sites.site_name AS siteName,
						orders.site_id,
						'' AS giveType,
						'' AS rechargeMoney,
						'' AS giveMoney,
						orders.created_at AS createdAt,
						orders.updated_at AS updatedAt 
					FROM
						lot_order orders,
						lot_user users,
						lot_site sites 
					WHERE
						orders.deleted_at IS NULL 
						AND users.id = orders.user_id 
						AND sites.id = orders.site_id 
					) t
				WHERE t.type in (1,2)
				ORDER BY
						t.updatedAt DESC
					LIMIT ?,?
				`
	// 通过原生sql 查询数组
	searchInfo, err := g.DB().GetAll(ctx, searchSql, g.Slice{startNum, endNum})
	_ = gconv.Scan(searchInfo, &res)
	return res, err
}
